<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="菜品名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入菜品名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          size="mini"
          @change="listStatusChange"
          clearable>
          <el-option label="在售" value="1" />
          <el-option label="下架" value="0" />
        </el-select>
      </el-form-item>

      <!-- 新增售卖类型下拉选择框 -->
      <el-form-item label="售卖类型" prop="typeId">
        <el-select
          v-model="queryParams.typeId"
          placeholder="请选择售卖类型"
          size="mini"
          @change="handleQuery"
          clearable>
          <el-option
            v-for="item in saleTypeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:product:export']"
        >导出</el-button>
      </el-col>
      <!-- 状态筛选下拉框 - 默认选中在售状态 -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="菜品名" align="center" prop="name" />
      <el-table-column label="菜品描述" align="center" prop="content" />
      <el-table-column label="价格" align="center" prop="amount" />
      <el-table-column label="剩余数量" align="center" prop="number" />
      <el-table-column label="初始库存" align="center" prop="max" />
      <el-table-column label="限购数" align="center" prop="limitNum" />
      <el-table-column label="图片" align="center" prop="url" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.url" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="领取时间" align="center" prop="claimTime" width="110"/>
      <el-table-column label="商品开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否上架" align="center" prop="isActive">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isActive"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
            disabled
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:product:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:product:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="80px">
        <!-- 新增售卖类型选择框 -->
        <el-form-item label="售卖类型" prop="typeId">
          <el-select
            v-model="form.typeId"
            placeholder="请选择售卖类型"
            clearable>
            <el-option
              v-for="item in saleTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜品名" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜品名" />
        </el-form-item>
        <el-form-item label="菜品描述" prop="content">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="价格" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入价格" type="number"/>
        </el-form-item>
        <el-form-item label="剩余数量" prop="number">
          <el-input v-model="form.number" placeholder="请输入剩余数量" type="number" />
        </el-form-item>
        <el-form-item label="商品初始库存" prop="max">
          <el-input v-model="form.max" placeholder="请输入商品初始库存" type="number" />
        </el-form-item>
        <el-form-item label="限购数" prop="limitNum">
          <el-input v-model="form.limitNum" placeholder="请输入限购数" type="number" />
        </el-form-item>
        <el-form-item label="图片" prop="url">
          <image-upload v-model="form.url" :limit="1"/>
        </el-form-item>
        <el-form-item label="领取时间" prop="claimTime">
          <el-date-picker
            clearable
            v-model="form.claimTime"
            type="datetime"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" 
            placeholder="请选择领取时间"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            clearable
            v-model="form.startTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            clearable
            v-model="form.endTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择结束时间"
          />
        </el-form-item>
        <!-- <el-form-item label="是否上架" prop="isActive">
          <el-switch
            v-model="form.isActive"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item> -->
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
  
</template>

<script setup name="Product">
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/system/product"
import { listSaleType } from "@/api/system/saleType" // 引入售卖类型API

const { proxy } = getCurrentInstance()

const productList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const saleTypeOptions = ref([]) // 售卖类型选项

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    status: "1", // 修复1：添加缺失的status属性
    startTime: null,
    endTime: null,
    isActive: null,
    typeId: null 
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 处理状态变更 */
function handleStatusChange(row) {
  const statusText = row.isActive === 1 ? '上架' : '下架'
  
  proxy.$modal.confirm(`确认要${statusText}菜品"${row.name}"吗？`).then(() => {
    // 构造更新数据对象，只传递需要更新的字段
    const updateData = {
      id: row.id,
      isActive: row.isActive
    }
    
    // 调用API更新状态
    return updateProduct(updateData)
  }).then(response => {
    proxy.$modal.msgSuccess("状态修改成功")
    getList() // 刷新列表确保数据同步
  }).catch(error => {
    // 用户取消操作或更新失败时回滚状态
    if (error !== 'cancel') {
      row.isActive = row.isActive === 1 ? 0 : 1
      proxy.$modal.msgError("状态修改失败")
      console.error("状态修改失败:", error)
    } else {
      // 用户取消操作时也回滚状态
      row.isActive = row.isActive === 1 ? 0 : 1
    }
  })
}
// 获取售卖类型数据
function getSaleTypeList() {
  listSaleType().then(response => {
    saleTypeOptions.value = response.rows || response.data
    
    // 页面刷新时自动选择第一个启用的售卖类型
    if (saleTypeOptions.value && saleTypeOptions.value.length > 0) {
      // 查找第一个状态为启用的售卖类型
      const enabledSaleType = saleTypeOptions.value.find(item => item.status === 1)
      if (enabledSaleType) {
        queryParams.value.typeId = enabledSaleType.id
      } else {
        // 如果没有启用的售卖类型，默认选择第一个
        queryParams.value.typeId = saleTypeOptions.value[0].id
      }
    }
     // 获取售卖类型后，重新加载菜品列表
    getList()
  })
}
// 修复2：修正状态筛选逻辑
function listStatusChange() {
  handleQuery()
}

/** 查询卤味列表 */
function getList() {
  loading.value = true
  // 根据状态设置isActive参数
  if (queryParams.value.status === '1') {
    queryParams.value.isActive = 1; // 在售状态
  } else {
    queryParams.value.isActive = null; // 全部状态
  }
  listProduct(queryParams.value).then(response => {
    productList.value = response.rows
    total.value = response.total
    loading.value = false
   
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    content: null,
    amount: null,
    number: null,
    max: null,
    limitNum: null,
    url: null,
    startTime: null,
    endTime: null,
    isActive: null,
    typeId: null
  }
  proxy.resetForm("productRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // 修复3：额外重置状态筛选条件
  queryParams.value.status = null
  queryParams.value.typeId = null 
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加卤味"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  // 修复4：正确处理单条修改的ID获取
  const _id = row ? row.id : ids.value[0]
  getProduct(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改卤味"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除卤味编号为"' + _ids + '"的数据项？').then(function() {
    return delProduct(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}
// 在组件初始化时获取售卖类型数据
getSaleTypeList()
getList()
</script>